Home Previous year paper Algorithms Notes About us
Write a program to calculate pow(x,n)

Given two integers x and n, write a function to compute x^n. We may assume that x and n are small and overflow doesn’t happen.

Examples :

Input : x = 2, n = 3
Output : 8

Input : x = 7, n = 2
Output : 49

// C++ program for the above approach

#include < bits/stdc++.h >

using namespace std;

int power(int x, int y)

{

int result = 1;

while (y > 0) {

if (y % 2 == 0) // y is even

{

x = x * x;

y = y / 2;

}

else // y isn't even

{

result = result * x;

y = y - 1;

}

}

return result;

}

// Driver Code

int main()

{

int x = 2;

int y = 3;

cout << (power(x, y));

return 0;

}

Output


8

Auxiliary Space: O(1)